package com.booking.service.impl;

import com.booking.common.utils.DtUtils;
import com.booking.controller.model.req.analyse.AnalyseQueryReq;
import com.booking.controller.model.res.OrderCountRes;
import com.booking.dao.entity.RoomOrder;
import com.booking.dao.entity.ServiceOrder;
import com.booking.dao.service.RoomOrderService;
import com.booking.dao.service.ServiceOrderService;
import com.booking.service.AnalyseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Qikai.Lin
 * @Date 2023/05/22
 */
@Service
public class AnalyseServiceImpl implements AnalyseService {

    @Autowired
    private RoomOrderService roomOrderService;
    @Autowired
    private ServiceOrderService serviceOrderService;

    @Override
    public OrderCountRes getOrderCount(AnalyseQueryReq request) {
        List<RoomOrder> roomOrders = roomOrderService.getListByCondition(request);
        List<ServiceOrder> serviceOrders = serviceOrderService.getListByCondition(request);
        Map<String, Integer> totalCountMap = new HashMap<>();
        // 统计roomOrders
        Map<LocalDateTime, List<RoomOrder>> roomCollect = roomOrders.stream().collect(Collectors.groupingBy(RoomOrder::getBookingDate));
        roomCollect.forEach( (dt, list) -> {
            String dtStr = DtUtils.getDtStr(dt);
            if (totalCountMap.containsKey(dtStr)) {
                totalCountMap.put(dtStr, totalCountMap.get(dtStr) + list.size());
            } else {
                totalCountMap.put(dtStr, list.size());
            }
        });

        // 统计serviceOrders
        Map<LocalDateTime, List<ServiceOrder>> serviceCollect = serviceOrders.stream().collect(Collectors.groupingBy(ServiceOrder::getBookingDate));
        serviceCollect.forEach( (dt, list) -> {
            String dtStr = DtUtils.getDtStr(dt);
            if (totalCountMap.containsKey(dtStr)) {
                totalCountMap.put(dtStr, totalCountMap.get(dtStr) + list.size());
            } else {
                totalCountMap.put(dtStr, list.size());
            }
        });
        // 排序
        Map<String, Integer> sortedCountMap = new HashMap<>();
        totalCountMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(e -> sortedCountMap.put(e.getKey(), e.getValue()));

        OrderCountRes res = new OrderCountRes();
        res.setCountList(new ArrayList<>(sortedCountMap.values()));
        res.setDtList(new ArrayList<>(sortedCountMap.keySet()));
        return res;
    }
}
